package com.turman.common.tab

import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.turman.builibrary.tab.bottom.BTabBottomInfo
import java.lang.Exception

class TabViewAdapter(
    private val mFragmentManager: FragmentManager,
    private val mInfoList: List<BTabBottomInfo<*>>
) {
    // 当前展示的framgnet实例
    var mCurrentFragment: Fragment?=null

    /**
     *  实例化以及显示指定的fragment
     * @author buobao
     * @since 2024/3/12 9:52
     */
    fun instantiateItem(container: View, position: Int) {
        val transaction = mFragmentManager.beginTransaction()
        //将当前展示fragment隐藏
        mCurrentFragment?.let {
            transaction.hide(it)
        }
        val name = "${container.id}:${position}"
        var fragment = mFragmentManager.findFragmentByTag(name)
        if (fragment != null) {
            //之前添加过直接展示
            transaction.show(fragment)
        } else {
            fragment = getItem(position)
            if (fragment?.isAdded==false) {
                transaction.add(container.id,fragment,name)
            }
        }
        mCurrentFragment = fragment
        transaction.commitAllowingStateLoss()
    }

    fun getCount():Int {
        return mInfoList.size
    }

    /**
    * 实例化fragment
    * @author buobao
    * @since 2024/3/12 9:55
    */
    private fun getItem(position: Int): Fragment? {
        try {
            return mInfoList.get(position).fragment.newInstance()
        } catch (e:Exception) {
            e.printStackTrace()
        }
        return null
    }
}